package com.sfac.java_spring_boot_02.interceptor;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description RequestViewMappingInterceptor
 * @Author HymanHu
 * @Date 2021/9/17 9:27
 */
@Component
public class RequestViewMappingInterceptor implements HandlerInterceptor {
    private final static Logger LOGGER =
            LoggerFactory.getLogger(RequestViewMappingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        LOGGER.debug("======== Pre Interceptor ========");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        // 判断：1、是否返回页面；2、是否重定向；3、是否转发
        if (modelAndView == null ||
                modelAndView.getViewName().startsWith("redirect") ||
                modelAndView.getViewName().startsWith("forward")) {
            return;
        }

        // 判断控制器里面是否有手动设置 template，手动设置优先
        String template = (String) modelAndView.getModelMap()
                .getAttribute("template");
        if (StringUtils.isBlank(template)) {
            String path = request.getServletPath();
            // 没有手动设置，将 path 路径设置到 modelmap 中 template 里
            modelAndView.getModelMap().addAttribute("template", path.substring(1));
        }

        LOGGER.debug("======== Post Interceptor ========");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LOGGER.debug("======== After Interceptor ========");
    }
}